/**
 * Created by xiongwei on 2017/5/6.
 */

import $$ from "utils"
import AppServer from '../common/AppService';
import HttpService from './HttpService';

function successHandler(resp, resolve, reject) {

  const {code, msg, status, message} = resp;

  if (code === 0 || code === '0000' || code === '000000') {
    resolve(resp.objList || resp.obj);
  } else {

    let str = "";
    if (!!code) {
      str = `请求错误 响应码:${code} 信息:${msg}`;
    } else {
      switch (status) {
        case 400:
          const errors = resp.errors;
          !!errors && errors.forEach(v => str += v.defaultMessage);
          str = `请求错误 响应码:${status} 信息:${msg}`;
          break;
        case 500:
          str = "请求服务器异常";
          break
        default:
          str = `请求错误 响应码:${status}`;
          break
      }
    }
    reject(str);
  }
};

function getToken() {
  const Token = JSON.parse(sessionStorage.getItem("userInfo"));
  return !!Token ? Token.access_token : null;
}

/**
 * Get
 * @param apiPath
 * @param headers
 * @param params
 * @param server
 * @returns {Promise.<TResult>}
 */
export async function commonGet(apiPath, headers, params, server = AppServer.baseUrl) {
  const url = `${server}${apiPath.indexOf('/') === 0 ? apiPath.substring(1) : apiPath}`;
  const dataServer = false;
  params.access_token = getToken();
  $$.debug('request.get:', url, headers, params);
  return new Promise((resolve, reject) => {
    HttpService.doGet(url, headers, params)
      .then(response => response.json())
      .then((resp) => {
        $$.debug(apiPath, resp);
        successHandler(resp, resolve, reject, dataServer);
      })
      .catch((err) => {
        $$.error("请求错误", url, err);
        reject("网络请求失败");
      });
  });
};

/**
 * 客户端通用的网络请求  TOKENhuoqu
 * @param apiPath
 * @param headers
 * @param params
 * @param server
 * @returns {Promise}
 */
export async function commonFormPostToken(apiPath, headers, params, server = AppServer.baseUrl) {
  const url = `${server}${apiPath.indexOf('/') === 0 ? apiPath.substring(1) : apiPath}`;

  $$.debug('request.form.post:', url, headers, params);
  return new Promise((resolve, reject) => {
    HttpService.doFormPost(url, headers, params)
      .then(response => response.json())
      .then((resp) => {
        $$.debug(apiPath, resp);
        resolve(resp);
      })
      .catch((err) => {
        $$.error("请求错误", url, err);
        reject("网络请求失败");
      });
  });
};


/**
 * 客户端通用的网络请求
 * @param apiPath
 * @param headers
 * @param params
 * @param server
 * @returns {Promise}
 */
export async function commonFormPost(apiPath, headers, params, server = AppServer.baseUrl) {
  const url = `${server}${apiPath.indexOf('/') === 0 ? apiPath.substring(1) : apiPath}`;
  $$.debug('request.form.post:', url, headers, params);
  params.access_token = getToken();
  return new Promise((resolve, reject) => {
    HttpService.doFormPost(url, headers, params)
      .then(response => response.json())
      .then((resp) => {
        $$.debug(apiPath, resp);
        successHandler(resp, resolve, reject);
      })
      .catch((err) => {
        $$.error("请求错误", url, err);
        reject("网络请求失败");
      });
  });
};


/**
 * REST形式的POST请求
 * @param apiPath
 * @param headers
 * @param params
 * @param server
 * @returns {Promise.<TResult>}
 */
export async function commonRestPost(apiPath, headers, params, server = AppServer.baseUrl) {
  const url = `${server}${apiPath.indexOf('/') === 0 ? apiPath.substring(1) : apiPath}`;
  params.access_token = getToken();
  return new Promise((resolve, reject) => {
    HttpService.doRestPost(url, headers, params)
      .then(response => response.json())
      .then((resp) => {
        // LogService.debug(apiPath, resp);
        successHandler(resp, resolve, reject);
      })
      .catch((err) => {
        $$.error("请求错误", url, err);
        reject("网络请求失败");
      });
  });
};

/**
 * put请求
 * @param apiPath
 * @param headers
 * @param params
 * @param server
 * @returns {Promise.<TResult>}
 */
export async function commonPut(apiPath, headers, params, server = AppServer.baseUrl) {
  const url = `${server}${apiPath.indexOf('/') === 0 ? apiPath.substring(1) : apiPath}`;
  params.access_token = getToken();
  console.log(params)
  return new Promise((resolve, reject) => {
    HttpService.doPut(url, headers, params)
      .then(response => response.json())
      .then((resp) => {
        // LogService.debug(apiPath, resp);
        successHandler(resp, resolve, reject);
      })
      .catch((err) => {
        $$.error("请求错误", url, err);
        reject("网络请求失败");
      });
  });
};

/**
 * DELETE请求
 * @param apiPath
 * @param headers
 * @param params
 * @param server
 * @returns {Promise.<TResult>}
 */
export async function commonDelete(apiPath, headers, params, server = AppServer.baseUrl) {
  const url = `${server}${apiPath.indexOf('/') === 0 ? apiPath.substring(1) : apiPath}`;
  return new Promise((resolve, reject) => {
    HttpService.doDelete(url, headers, params)
      .then(response => response.json())
      .then((resp) => {
        $$.debug(apiPath, resp);
        successHandler(resp, resolve, reject);
      })
      .catch((err) => {
        $$.error("请求错误", url, err);
        reject("网络请求失败");
      });
  });
};
